from flask import Flask,request,session,redirect
from .view import account
from .view import order
from .view import task
from .view import user
import config
from .task import task1
from flask_apscheduler import APScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Blueprint,render_template,request,redirect,session
from demo1.utils import DbConfigUtils




def auth():
    if request.path.startswith("/static"):
        return
    if request.path=='/login':
        # 继续向后执行 不拦截
        return
    user_info=session.get('user_info')
    if  user_info:
        return
    return redirect('/login')

def create_app():
    app=Flask(__name__)
    app.secret_key='1234ddsadasdsds56'
    #  注册蓝图
    app.register_blueprint(account.ac)
    app.register_blueprint(order.od)
    app.register_blueprint(task.task)
    app.register_blueprint(user.us)
    app.before_request(auth)
    # 配置执行器
    app.config['SCHEDULER_EXECUTORS'] = {'default': {'type': 'threadpool', 'max_workers': 10}}
    # 配置作业存储器
    app.config['SCHEDULER_JOBSTORES'] = {'default': {'type': 'memory'}}
    app.config.from_object(config.Config)
    # 创建APScheduler对象，调度器是BackgroundScheduler
    scheduler = APScheduler(scheduler=BackgroundScheduler(daemon=True))
    scheduler.init_app(app)
    scheduler.start()
    scheduler.add_job(id='do_job_1', func=task1.api_task, trigger='interval', seconds=1)
    # 添加新任务
    scheduler.add_job(id='do_job_2', func=task1.api_task1, trigger='interval', seconds=5)
    return  app


# scheduler_loader.py
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
import importlib

def load_jobs_from_db(scheduler, db):
    with db.connect() as conn:
        result = DbConfigUtils.fetchAll("SELECT * FROM scheduled_jobs WHERE enabled = TRUE")
        for row in result:
            job_id = row['id']
            func_name = row['func_name']
            trigger_type = row['trigger_type']

            # 动态导入函数
            module_name, func_name = func_name.rsplit('.', 1)
            module = importlib.import_module(module_name)
            func = getattr(module, func_name)

            # 构建触发器
            if trigger_type == 'cron':
                trigger = CronTrigger(
                    hour=row['hour'],
                    minute=row['minute'],
                    second=row['second'],
                    day_of_week=row['day_of_week']
                )
            elif trigger_type == 'interval':
                trigger = IntervalTrigger(seconds=int(row['second']))
            else:
                continue  # 跳过不支持的触发器类型

            # 添加任务
            scheduler.add_job(func=func, trigger=trigger, id=job_id, replace_existing=True)





